// select onchange函数
function selectClick(event) {
}

function load_data() {
    const show_data = document.getElementById('md_2_select').value;
    // 将数据名称发送到后台
    // 发起 AJAX 请求
  fetch(`/index/lab/load_data/?show_data=${show_data}`, {
    method: 'GET',
    headers: {
      'X-Requested-With': 'XMLHttpRequest'
    }
  })
  .then(response => response.json())
  .then(data => {
    // 请求成功后更新该module的样式
    render_module_page(data)
  })
  .catch(error => console.error('Error:', error));
}

function update_tactic_cont(data) {
    // 为横向排列的三个子容器填充select tactics标签
    const model_data = data.model_data;

    const filter_ls = model_data.lab_var_part2_3.filter_ls;
    const open_ls = model_data.lab_var_part2_3.open_ls;
    const close_ls = model_data.lab_var_part2_3.close_ls;
    // --------------------1-------------------------
    // Select the container div by its ID
    const container1 = document.getElementById("md_3_cont1");

    // Clear initial content
    container1.innerHTML = '';
    const div_class_name = "rounded tactic-bg p-2 mt-1 text-center";

    // Loop through the list and add each item as a new div
    filter_ls.forEach(text => {
        const newDiv = document.createElement("div");
        newDiv.textContent = text;
        newDiv.className = div_class_name; // Bootstrap 圆角和灰色背景
        // 绑定点击事件
        newDiv.onclick = function(event) {
            tacticDivClick(text);
        };
        newDiv.style.width = "100%"; // Make div fill the parent container horizontally
        newDiv.style.textAlign = "center"; // Optional: Center text within each div
        container1.appendChild(newDiv);
    });
    // --------------------2-------------------------
    // Select the container div by its ID
    const container2 = document.getElementById("md_3_cont2");

    // Clear initial content
    container2.innerHTML = '';

    // Loop through the list and add each item as a new div
    open_ls.forEach(text => {
        const newDiv = document.createElement("div");
        newDiv.textContent = text;
        newDiv.className = div_class_name; // Bootstrap 圆角和灰色背景
        // 绑定点击事件
        newDiv.onclick = function(event) {
            tacticDivClick(text);
        };
        newDiv.style.width = "100%"; // Make div fill the parent container horizontally
        newDiv.style.textAlign = "center"; // Optional: Center text within each div
        container2.appendChild(newDiv);
    });
    // --------------------3-------------------------
    // Select the container div by its ID
    const container3 = document.getElementById("md_3_cont3");

    // Clear initial content
    container3.innerHTML = '';

    // Loop through the list and add each item as a new div
    close_ls.forEach(text => {
        const newDiv = document.createElement("div");
        newDiv.textContent = text;
        newDiv.className = div_class_name; // Bootstrap 圆角和灰色背景
        // 绑定点击事件
        newDiv.onclick = function(event) {
            tacticDivClick(text);
        };
        newDiv.style.width = "100%"; // Make div fill the parent container horizontally
        newDiv.style.textAlign = "center"; // Optional: Center text within each div
        container3.appendChild(newDiv);
    });
}

function tactic_change(selectElement, event) {
    // 发起 AJAX 请求
  fetch(`/index/lab/add_tactic/?selected_tactic=${selectElement.value}`, {
    method: 'GET',
    headers: {
      'X-Requested-With': 'XMLHttpRequest'
    }
  })
  .then(response => response.json())
  .then(data => {
    // 请求成功后重置 select 的选项状态
    selectElement.selectedIndex = -1;
    update_tactic_cont(data)
  })
  .catch(error => console.error('Error:', error));
}

function tacticDivClick(textContent) {
    fetch(`/index/lab/remove_tactic/?remove_tactic=${textContent}`, {
        method: 'GET',
        headers: {
          'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => response.json())
    .then(data => {
        // 根据返回model_data更新tactic div相关内容
        update_tactic_cont(data)
    })
    .catch(error => console.error('Error:', error));
}

function tactic_ok() {
    // 发送确认请求，根据返回结果渲染
    fetch(`/index/lab/tactic_ok/`, {
        method: 'GET',
        headers: {
          'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => response.json())
    .then(data => {
        // 根据返回model_data更新tactic div相关内容
        render_module_page(data)
    })
    .catch(error => console.error('Error:', error));
}

function get_factor() {
    // 发送确认请求，根据返回结果渲染
    fetch(`/index/lab/get_factor/`, {
        method: 'GET',
        headers: {
          'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => response.json())
    .then(data => {
        // 根据返回model_data更新tactic div相关内容
        render_module_page(data)
    })
    .catch(error => console.error('Error:', error));
}

function change_dir() {
    // 发送确认请求，根据返回结果渲染
    fetch(`/index/lab/change_dir/`, {
        method: 'GET',
        headers: {
          'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => response.json())
    .then(data => {
        // 对返回的数据进行处理，一般不需要，因为该步骤
        render_module_page(data);
    })
    .catch(error => console.error('Error:', error));
}

function start_backtest() {
    // 发送确认请求，根据返回结果渲染
    fetch(`/index/lab/start_backtest/`, {
        method: 'GET',
        headers: {
          'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => response.json())
    .then(data => {
        // 对返回的数据进行处理，一般不需要，因为该步骤
        render_module_page(data);
    })
    .catch(error => console.error('Error:', error));
}

function render_list_page(data) {
    // 更新页面内容
    if ('model_list' in data) {
        let modelList = document.getElementById('model-list');
        modelList.innerHTML = "";  // 清空
        // 创建一个 Bootstrap 列表组
        let listGroup = document.createElement('div');
        listGroup.className = "list-group";  // 添加 Bootstrap 样式

        // 给part1 列表部分渲染数据
        for (let item of data.model_list) {
            // 创建卡片链接
            let card_component = document.createElement('a');
            card_component.className = "card text-decoration-none mb-1";
            card_component.href = `/index/lab/lab?model_name=${item[0]}`
            // 添加卡片头
            let card_header = document.createElement('div');
            card_header.className = "card-header text-center d-flex justify-content-between align-items-center";
            card_header.textContent = item[0];  // 主标题

            // 创建按钮容器
            let buttonContainer = document.createElement('div');
            buttonContainer.className = "d-flex";  // 横向布局

            // 创建显示 修改 的按钮
            let starButton = document.createElement('button');
            starButton.className = "btn btn-outline-primary cus-sm-btn";  // Bootstrap 按钮样式
            let icon = document.createElement('i');
            icon.className = "bi bi-pencil";
            starButton.appendChild(icon);
            starButton.onclick = function(event) {
                event.preventDefault();  // 阻止默认的链接跳转
                event.stopPropagation(); // 阻止事件冒泡
                openModalWithDefaults("modifyModal", [item[0], item[1]])
            }

            buttonContainer.appendChild(starButton);  // 添加按钮到容器

            // 创建显示 删除 的按钮
            let hashButton = document.createElement('button');
            hashButton.className = "btn btn-outline-primary cus-sm-btn";  // Bootstrap 按钮样式
            let icon1 = document.createElement('i');
            icon1.className = "bi bi-trash";
            hashButton.appendChild(icon1);
            hashButton.onclick = function(event) {
                event.preventDefault();  // 阻止默认的链接跳转
                event.stopPropagation(); // 阻止事件冒泡
                openModalWithDefaults("deleteModal", [item[0], item[1]])
            }

            buttonContainer.appendChild(hashButton);  // 添加按钮到容器
            card_header.appendChild(buttonContainer)
            card_component.appendChild(card_header);
            // 添加卡片体
            let card_body = document.createElement('div');
            card_body.className = "card-body p-2";
            /// 给卡片体添加内容
            let card_sub_title = document.createElement('p');
            card_sub_title.textContent = item[1].length > 30 ? item[1].slice(0, 30) + '...' : item[1];  // 副标题
            card_body.appendChild(card_sub_title);
            card_component.appendChild(card_body);
            listGroup.appendChild(card_component);
        }

        // 将列表组添加到模型列表容器中
        modelList.appendChild(listGroup);
    }
    if ('model_data' in data) {
        // 处理 model_data 的逻辑
        // 标记当前活跃的model对应列表为突出显示
        let now_model = data.model_data.lab_var_part2_1.title;
        // 根据title将列表中相应项突出
        // 获取list-group中所有的a标签
        const list_group = document.querySelector('.list-group');
        const a_labels = list_group.querySelectorAll('a');
        // 遍历a标签
        let a_label = null;
        for (a_label_o of a_labels) {
            const cardHeaderDiv = a_label_o.querySelector('.card-header');
            // 检查a元素下的类为card_header的div的文本内容是否为now_model
            if (cardHeaderDiv && cardHeaderDiv.textContent.trim() === now_model) {
                a_label = a_label_o;
                a_label_o.className = a_label_o.className + " model_selected"
                // 跳出循环
                break;
            }
        }
        // 此时，如果找到了文本内容为now_model的啊元素，则a_label变量将引用它
        // 如果没有找到，则h5变量将是h5Elements数组的最后一个元素（或者undefined，如果数组为空）
        // 检查我们是否确实找到了文本内容为now_model的h5元素
        if (a_label) {
            ;
        } else {
            // 如果没有找到，输出相应信息
            console.log('No h5 element with text content now_model found.');
        }
    }
}

function render_module_page(data) {
    // 渲染module和operate
    const model_data = data.model_data;
    // 获取第一组
    let module_1_div = document.getElementById("module_1");
    let module_1_card = document.getElementById("module_1_card");

    // 根据执行状态添加module样式
    if (true) {
        module_1_card.classList.add('module_executed');
    }else {
        module_1_card.classList.remove('module_executed');
    }
    // 更改其下相关标签的值
    module_1_div.querySelector("#md_1_title").innerText = model_data.lab_var_part2_1.title;
    module_1_div.querySelector("#md_1_subtitle").innerText = model_data.lab_var_part2_1.sub_title;
    // 获取第二组
    let module_2_div = document.getElementById("module_2");
    let module_2_card = document.getElementById("module_2_card");
    // 根据执行状态添加module样式
    if (model_data.lab_var_part2_2.execute) {
        module_2_card.classList.add('module_executed');
    }else {
        module_2_card.classList.remove('module_executed');
    }

    let module_2_select = document.getElementById("md_2_select");
    module_2_select.innerHTML = "";  // 清空所有标签
    // 创建一个option标签
//    let firstOption = document.createElement("option");
//    firstOption.selected = true;
//    firstOption.textContent = model_data.lab_var_part2_2.selected_data_ls[0];
//    module_2_select.appendChild(firstOption);
    // 使用 JavaScript 模拟生成其他 <option> 标签
    const options = model_data.lab_var_part2_2.selected_data_ls; // 假设 options 为一个 JavaScript 数组，包含所有 option 的值

    options.forEach(option => {
        let newOption = document.createElement("option");
        newOption.value = option;
        newOption.textContent = option;
        module_2_select.appendChild(newOption);
    });

    // 获取第三组
    let module_3_div = document.getElementById("module_3");
    let module_3_card = document.getElementById("module_3_card");
    // 根据执行状态添加module样式
    if (model_data.lab_var_part2_3.execute) {
        module_3_card.classList.add('module_executed');
    }else {
        module_3_card.classList.remove('module_executed');
    }

    let module_3_select = document.getElementById("md_3_select");
    module_3_select.innerHTML = "";  // 清空所有标签
    // 创建一个option标签
//    let md3_firstOption = document.createElement("option");
//    md3_firstOption.selected = true;
//    md3_firstOption.textContent = model_data.lab_var_part2_3.selected_tactics_ls[0];
//    module_3_select.appendChild(md3_firstOption);
    // 使用 JavaScript 模拟生成其他 <option> 标签
    const md3_options = model_data.lab_var_part2_3.selected_tactics_ls; // 假设 options 为一个 JavaScript 数组，包含所有 option 的值

    md3_options.forEach(option => {
        let newOption = document.createElement("option");
        newOption.value = option;
        newOption.textContent = option;
        module_3_select.appendChild(newOption);
    });
    // 重置select的展示项
    module_3_select.selectedIndex = -1;

    // 为横向排列的三个子容器填充select tactics标签
    const filter_ls = model_data.lab_var_part2_3.filter_ls;
    const open_ls = model_data.lab_var_part2_3.open_ls;
    const close_ls = model_data.lab_var_part2_3.close_ls;
    // --------------------1-------------------------
    // Select the container div by its ID
    const container1 = document.getElementById("md_3_cont1");

    // Clear initial content
    container1.innerHTML = '';
    const div_class_name = "rounded tactic-bg p-2 mt-1 text-center";

    // Loop through the list and add each item as a new div
    filter_ls.forEach(text => {
        const newDiv = document.createElement("div");
        newDiv.textContent = text;
        newDiv.className = div_class_name; // Bootstrap 圆角和灰色背景
        // 绑定点击事件
        newDiv.onclick = function(event) {
            tacticDivClick(text);
        };
        newDiv.style.width = "100%"; // Make div fill the parent container horizontally
        newDiv.style.textAlign = "center"; // Optional: Center text within each div
        container1.appendChild(newDiv);
    });
    // --------------------2-------------------------
    // Select the container div by its ID
    const container2 = document.getElementById("md_3_cont2");

    // Clear initial content
    container2.innerHTML = '';

    // Loop through the list and add each item as a new div
    open_ls.forEach(text => {
        const newDiv = document.createElement("div");
        newDiv.textContent = text;
        newDiv.className = div_class_name; // Bootstrap 圆角和灰色背景
        // 绑定点击事件
        newDiv.onclick = function() {
            tacticDivClick(text);
        };
        newDiv.style.width = "100%"; // Make div fill the parent container horizontally
        newDiv.style.textAlign = "center"; // Optional: Center text within each div
        container2.appendChild(newDiv);
    });
    // --------------------3-------------------------
    // Select the container div by its ID
    const container3 = document.getElementById("md_3_cont3");

    // Clear initial content
    container3.innerHTML = '';

    // Loop through the list and add each item as a new div
    close_ls.forEach(text => {
        const newDiv = document.createElement("div");
        newDiv.textContent = text;
        newDiv.className = div_class_name; // Bootstrap 圆角和灰色背景
        // 绑定点击事件
        newDiv.onclick = function() {
            tacticDivClick(text);
        };
        newDiv.style.width = "100%"; // Make div fill the parent container horizontally
        newDiv.style.textAlign = "center"; // Optional: Center text within each div
        container3.appendChild(newDiv);
    });

    // 获取第四组
    let module_4_div = document.getElementById("module_4");
    let module_4_card = document.getElementById("module_4_card");
    // 根据执行状态添加module样式
    if (model_data.lab_var_part2_4.execute) {
        module_4_card.classList.add('module_executed');
    }else {
        module_4_card.classList.remove('module_executed');
    }

    let md_4_div = document.getElementById("md_4_div");
    // 在其中填充一些因子名
    const tactics_factor_ls = model_data.lab_var_part2_4.tactics_factor_ls;
        // Clear initial content
    md_4_div.textContent = tactics_factor_ls;
//    md_4_div.innerHTML = '';
//
//    // Loop through the list and add each item as a new div
//    tactics_factor_ls.forEach(text => {
//        const newDiv = document.createElement("div");
//        newDiv.textContent = text;
//        newDiv.style.width = "100%"; // Make div fill the parent container horizontally
//        newDiv.style.textAlign = "center"; // Optional: Center text within each div
//        md_4_div.appendChild(newDiv);
//    });

    // 获取第五组
    let module_5_div = document.getElementById("module_5");
    let module_5_card = document.getElementById("module_5_card");
    let strategy_direction_div = document.getElementById("strategy_direction");
    if (model_data.strategy_direction == 1) {
        strategy_direction_div.textContent = "看多策略"
    }else if (model_data.strategy_direction == -1) {
        strategy_direction_div.textContent = "看空策略"
    }

    // 根据执行状态添加module样式
    if (model_data.lab_var_part2_5.execute) {
        module_5_card.classList.add('module_executed');
    }else {
        module_5_card.classList.remove('module_executed');
    }



    // 默认显示operate1对应的Operate界面
//    // 获取操作容器
//    const operate_container = document.getElementById('operate_container');
//
//    // 删除已有的 iframe（如果存在）
//    const existingIframe = operate_container.querySelector('iframe');
//    const iframe_url = existingIframe ? existingIframe.src : '/operate/overview_page/';
//    if (existingIframe) {
//        operate_container.removeChild(existingIframe);
//    }
//    // 创建新的 iframe 元素
//    const newIframe = document.createElement('iframe');
//    newIframe.id = "operate1";
//    newIframe.style.width = '100%';
//    newIframe.style.height = 'calc(100vh - 12rem)';
//    newIframe.style.border = 'none';
//    newIframe.src = iframe_url;
//
//    // 将新的 iframe 添加到容器中
//    operate_container.appendChild(newIframe);
}



window.render_list_page = render_list_page;
window.render_module_page = render_module_page;



